import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/utils/color_util.dart';
import 'package:xinxuan/vo/upload_image_vo.dart';

class UploadUtil {

  /// 上传图片
  Future<List<UploadImageData>> uploadImage({required BuildContext context, int maxAssets = 9, int style = 1, String module = 'identity'}) async {
    List<AssetEntity>? assets = await AssetPicker.pickAssets(
      context, 
      maxAssets: maxAssets, 
      themeColor: bgMainColor,
      // sortPathDelegate: CustomMySortPathDelegate()
    );
    if (assets == null) {
      return [];
    }
    List<UploadImageData> _imageArr = [];
    await Future.forEach(assets, (item) async {
      File? _file = await assets[0].originFile;
      MultipartFile multipartFile = await MultipartFile.fromFile(_file!.path);
      FormData formData = FormData.fromMap({'image': multipartFile, 'module': module, 'style': style});
      UploadImageVo _uploadImageVo = await HttpUtilService.uploadImage(formData);
      _imageArr.add(_uploadImageVo.data!);
    });
    return _imageArr;
  }

  /// 使用相机上传图片
  Future<List<UploadImageData>> uploadImageFromCamera({int style = 1, String module = 'identity'}) async {
    List<UploadImageData> _imageArr = [];
    final ImagePicker _picker = ImagePicker();
    final XFile? images = await _picker.pickImage(
      source: ImageSource.camera,
    );
    if (images != null) {
      List<int> uint8list = await images.readAsBytes();
      MultipartFile multipartFile = MultipartFile.fromBytes(uint8list, filename: images.name);
      FormData formData = FormData.fromMap({'image': multipartFile, 'module': module, 'style': style});
      UploadImageVo _uploadImageVo = await HttpUtilService.uploadImage(formData);
      _imageArr.add(_uploadImageVo.data!);
    }
    return _imageArr;
  }
}